package top.jacktgq.itheima.netty.future.close;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @Author CandyWall
 * @Date 2021/3/22--21:02
 * @Description
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG)).addLast(new StringEncoder());
                    }
                })
                // 异步非阻塞，main发起了调用，真正执行connect是nio线程
                .connect("localhost", 8080);
        Channel channel = channelFuture.sync().channel();

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            String content = "";
            do {
                content = scanner.nextLine();
                channel.writeAndFlush(content);
            } while (!content.equals("close"));
            channel.close();
            // 错误地关闭客户端的做法
            // 由于通道的关闭操作是异步的，所以不能直接将关闭客户端的代码直接写到channel.close()代码之后
            // log.debug("处理关闭之后的操作...");
        }).start();

        // 正确的关闭客户端的做法
        // 获取closeFuture对象
        ChannelFuture closeFuture = channel.closeFuture();

        // 做法1：同步处理关闭；
        // 主线程会阻塞住，等待channel.close()关闭之后，才会继续向下执行
        /*closeFuture.sync();
        log.debug("处理关闭之后的操作...");*/

        // 做法2：异步处理关闭
        closeFuture.addListener(future -> {
            log.debug("处理关闭之后的操作...");
            group.shutdownGracefully();
            /*Future f = group.shutdownGracefully();
            f.addListener(f1 -> {
                f.get();
                if (f == f1)
                    System.out.println("closed");
                else {
                    System.out.println("cannot close");
                }
            });*/
            log.debug("事件循环组已经关闭...");
        });
    }
}
